package com.wzx.goods.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wzx.goods.dao.BrandDao;
import com.wzx.goods.pojo.Brand;
import com.wzx.goods.service.BrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.StringUtil;

import java.util.List;

@Service
public class BrandServiceImpl implements BrandService {
    @Autowired
    BrandDao brandDao;
    @Override
    public List<Brand> findAll() {
        return brandDao.selectAll();
    }

    @Override
    public Brand findById(int id) {
        return brandDao.selectByPrimaryKey(id);
    }

    @Override
    public void deleteById(int id) {
        brandDao.deleteByPrimaryKey(id);
    }

    @Override
    public void saveBrand(Brand brand) {
        brandDao.insert(brand);
    }

    @Override
    public void updateBrand(Brand brand) {

        brandDao.updateByPrimaryKey(brand);
    }

    @Override
    public List<Brand> findList(Brand brand) {//brand看表单输入的对象

        Example example = getExample(brand);
        return brandDao.selectByExample(example);
    }
    private Example getExample(Brand brand){
        //Example 表示高级搜索的条件
        Example example = new Example(Brand.class);//参1 对应 tb_brand
        //高级搜索页面输入的值作为条件 where

        Example.Criteria criteria = example.createCriteria();
        if (brand != null) {
            //如果用户在高级搜索表单里面有输入值 ，表示用户在按该条件查找
            //名称
            if (!StringUtils.isEmpty(brand.getName())) {
                criteria.andLike("name", "%" + brand.getName() + "%");
            }

            //图片
            if (!StringUtils.isEmpty(brand.getImage() )) {
                criteria.andLike("image", "%" + brand.getImage() + "%");
            }
            //字母
            if (!StringUtils.isEmpty(brand.getLetter() )) {
                //and letter like '%A%'
                criteria.andLike("letter", "%" + brand.getLetter() + "%");
            }
            //id
            if (!StringUtils.isEmpty(brand.getId() )) { //null +"" => "null"
                criteria.andEqualTo("id", brand.getId());
            }
            //seq
            if (!StringUtils.isEmpty(brand.getSeq())) {
                criteria.andEqualTo("seq", brand.getSeq());
            }
        }
        return example;
    }

    @Override
    public PageInfo<Brand> findPage(Brand brand, int curr, int pageSize) {
        //分页，使用了mybatis的分页插件
        PageHelper.startPage(curr,pageSize); //limit curr,pageSize
        //查询
        Example example = getExample(brand);
        List<Brand> list = brandDao.selectByExample(example);
        PageInfo<Brand> pi = new PageInfo<>(list);
        return pi;
    }
}
